package org.jeecg.modules.demo.mytest.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.mytest.entity.MtProject;
import org.jeecg.modules.demo.mytest.entity.MtProjectDocument;
import org.jeecg.modules.demo.mytest.service.IMtProjectDocumentService;
import org.jeecg.modules.demo.mytest.service.IMtProjectService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 项目表
 * @Author: thankgod7
 * @Date: 2023-07-28
 * @Version: V1.0
 */
@Api(tags = "项目表")
@RestController
@RequestMapping("/mytest/mtProject")
@Slf4j
public class MtProjectController extends JeecgController<MtProject, IMtProjectService> {

    @Resource
    private IMtProjectService mtProjectService;

    @Resource
    private IMtProjectDocumentService mtProjectDocumentService;


    /*---------------------------------主表处理-begin-------------------------------------*/

    @ApiOperation(value = "项目表-分页列表查询", notes = "项目表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MtProject>> queryPageList(MtProject mtProject,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                  HttpServletRequest req) {
        if (StringUtils.isNotBlank(mtProject.getCategoryCode())) {
            mtProject.setCategoryCode(mtProject.getCategoryCode() + "*");
        }
        QueryWrapper<MtProject> queryWrapper = QueryGenerator.initQueryWrapper(mtProject, req.getParameterMap());
        Page<MtProject> page = new Page<>(pageNo, pageSize);
        IPage<MtProject> pageList = mtProjectService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "项目表-添加")
    @ApiOperation(value = "项目表-添加", notes = "项目表-添加")
    @RequiresPermissions("mytest:mt_project:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MtProject mtProject) {
        mtProjectService.save(mtProject);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "项目表-编辑")
    @ApiOperation(value = "项目表-编辑", notes = "项目表-编辑")
    @RequiresPermissions("mytest:mt_project:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MtProject mtProject) {
        mtProjectService.updateById(mtProject);
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "项目表-通过id删除")
    @ApiOperation(value = "项目表-通过id删除", notes = "项目表-通过id删除")
    @RequiresPermissions("mytest:mt_project:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id") String id) {
        mtProjectService.delMain(id);
        return Result.OK("删除成功!");
    }

    @AutoLog(value = "项目表-批量删除")
    @ApiOperation(value = "项目表-批量删除", notes = "项目表-批量删除")
    @RequiresPermissions("mytest:mt_project:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids") String ids) {
        this.mtProjectService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    @RequiresPermissions("mytest:mt_project:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MtProject mtProject) {
        return super.exportXls(request, mtProject, MtProject.class, "项目表");
    }

    @RequiresPermissions("mytest:mt_project:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MtProject.class);
    }
    /*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-项目文档表-begin----------------------------------------------*/

    @ApiOperation(value = "项目文档表-通过主表ID查询", notes = "项目文档表-通过主表ID查询")
    @GetMapping(value = "/listMtProjectDocumentByMainId")
    public Result<IPage<MtProjectDocument>> listMtProjectDocumentByMainId(MtProjectDocument mtProjectDocument,
                                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                          HttpServletRequest req) {
        QueryWrapper<MtProjectDocument> queryWrapper = QueryGenerator.initQueryWrapper(mtProjectDocument, req.getParameterMap());
        Page<MtProjectDocument> page = new Page<>(pageNo, pageSize);
        IPage<MtProjectDocument> pageList = mtProjectDocumentService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "项目文档表-添加")
    @Transactional(rollbackFor = Throwable.class)
    @ApiOperation(value = "项目文档表-添加", notes = "项目文档表-添加")
    @PostMapping(value = "/addMtProjectDocument")
    public Result<String> addMtProjectDocument(@RequestBody MtProjectDocument mtProjectDocument) {
        mtProjectDocumentService.save(mtProjectDocument);
        mtProjectDocumentService.reCount(mtProjectDocument.getId());
        mtProjectService.reCount(mtProjectDocument.getProjectId());
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "项目文档表-编辑")
    @Transactional(rollbackFor = Throwable.class)
    @ApiOperation(value = "项目文档表-编辑", notes = "项目文档表-编辑")
    @RequestMapping(value = "/editMtProjectDocument", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> editMtProjectDocument(@RequestBody MtProjectDocument mtProjectDocument) {
        mtProjectDocumentService.updateById(mtProjectDocument);
        mtProjectDocumentService.reCount(mtProjectDocument.getId());
        mtProjectService.reCount(mtProjectDocument.getProjectId());
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "项目文档表-通过id删除")
    @Transactional(rollbackFor = Throwable.class)
    @ApiOperation(value = "项目文档表-通过id删除", notes = "项目文档表-通过id删除")
    @DeleteMapping(value = "/deleteMtProjectDocument")
    public Result<String> deleteMtProjectDocument(@RequestParam(name = "id") String id) {
        MtProjectDocument document = mtProjectDocumentService.getById(id);
        if (Objects.nonNull(document)) {
            mtProjectDocumentService.removeById(id);
            mtProjectDocumentService.reCount(id);
            mtProjectService.reCount(document.getProjectId());
        }
        return Result.OK("删除成功!");
    }

    @AutoLog(value = "项目文档表-批量删除")
    @Transactional(rollbackFor = Throwable.class)
    @ApiOperation(value = "项目文档表-批量删除", notes = "项目文档表-批量删除")
    @DeleteMapping(value = "/deleteBatchMtProjectDocument")
    public Result<String> deleteBatchMtProjectDocument(@RequestParam(name = "ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<MtProjectDocument> documentList = mtProjectDocumentService.listByIds(idList);
        if (documentList.size() > 0) {
            this.mtProjectDocumentService.removeByIds(idList);
            idList.forEach(id -> mtProjectDocumentService.reCount(id));
            mtProjectService.reCount(documentList.get(0).getProjectId());
        }
        return Result.OK("批量删除成功!");
    }

    @RequestMapping(value = "/exportMtProjectDocument")
    public ModelAndView exportMtProjectDocument(HttpServletRequest request, MtProjectDocument mtProjectDocument) {
        // Step.1 组装查询条件
        QueryWrapper<MtProjectDocument> queryWrapper = QueryGenerator.initQueryWrapper(mtProjectDocument, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<MtProjectDocument> pageList = mtProjectDocumentService.list(queryWrapper);
        List<MtProjectDocument> exportList;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, "项目文档表");
        mv.addObject(NormalExcelConstants.CLASS, MtProjectDocument.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("项目文档表报表", "导出人:" + sysUser.getRealname(), "项目文档表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    @RequestMapping(value = "/importMtProjectDocument/{mainId}")
    public Result<?> importMtProjectDocument(HttpServletRequest request, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MtProjectDocument> list = ExcelImportUtil.importExcel(file.getInputStream(), MtProjectDocument.class, params);
                for (MtProjectDocument temp : list) {
                    temp.setProjectId(mainId);
                }
                long start = System.currentTimeMillis();
                mtProjectDocumentService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.OK("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-项目文档表-end----------------------------------------------*/


}
